package cn.itcast.service;

import cn.itcast.dao.SetmealDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.CheckGroup;
import cn.itcast.pojo.Setmeal;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 *Author:TH
 *Dete:2019/10/2019:51
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {


    @Autowired
    private SetmealDao setmealDao;

    //添加检查套餐信息
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加套餐信息
        setmealDao.add(setmeal);

        //添加检查套餐与检查组关系
        addSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
    }

    //添加检查套餐与检查组关系
    public void addSetmealAndCheckGroup(Integer setmeal_id,Integer[] checkgroupIds){

        if (checkgroupIds!=null&&checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<String,Integer>();
                map.put("setmeal_id",setmeal_id);
                map.put("checkgroup_id",checkgroupId);
                setmealDao.addSetmealAndCheckGroup(map);
            }
        }
    }

    //分页查询
    public PageResult pageQuery(Integer cp, Integer ps, String qs) {
        PageHelper.startPage(cp,ps);
        Page<CheckGroup> page = setmealDao.findByCondition(qs);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //查询所有套餐信息
    public List<Setmeal> findAll() {

        return setmealDao.findAll();
    }

    @Override
    public Setmeal findBysId(Integer id) {
        return setmealDao.findBysId(id);
    }
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    //修改套餐信息
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {

        //删除检查组所有的检查项
        setmealDao.deleteAssociation(setmeal.getId());
        //建立新的检查组与检查相关系
        addSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        //更新检查组信息
        setmealDao.edit(setmeal);

    }


    //查询该套餐所有的检查项
    public List<Integer> findCheckGroupIdsBysetmealId(Integer id) {
        return setmealDao.findCheckGroupIdsBysetmealId(id);
    }

    @Override
    public List<Map<String, Object>> findfindSetmealCount() {
        return setmealDao.findfindSetmealCount();
    }

}
